package com.neuedu.aop.adivce;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Component;

import java.lang.reflect.Executable;
import java.rmi.server.ExportException;


@Component
@Aspect     //@Aspect定义此类为方面代码，即是一个通知。
public class MyAdvice {


    /**
     *    定义一个切点  execution(* com.neuedu.aop.service.*.insert(..))
     *       第一个* 代表 类型
     *        insert 代表 这些类中所有 insert方法
     */

    @Pointcut("execution(* com.neuedu.aop.service.*.insert(..))")
    public void insertMethod(){}


    @Pointcut("execution(* com.neuedu.aop.service.*.update(..))")
    public void updateMethod(){}


    @Pointcut("execution(* com.neuedu.aop.service.*.selectById(..))")
    public void selectByIdMethod(){}

    @Pointcut("execution(* com.neuedu.aop.service.*.save(..))")
    public void saveMethod(){}

    /**
     *  前置通知
     * @param joinpoint
     */
    @Before("insertMethod()")
    public void beforeMethod(JoinPoint joinpoint){
        System.out.println("【前置通知日志】" + joinpoint.toString());
    }


    // @After("updateMethod()")
    @After(value="updateMethod()")
    public void afterMethod(JoinPoint joinpoint){
        System.out.println("【后置通知日志】" + joinpoint.toString());
    }

    // @AfterReturning(value="selectByIdMethod()",returning="result")
    // public void afterReturingMethod(JoinPoint joinpoint ,Object result){
    //     System.out.println("【AfterReturing 通知】" + joinpoint.toString());
    //     System.out.println("result = " + result);
    // }


    @AfterThrowing(value="selectByIdMethod()",throwing="ex")
    public void afterReturingMethod(JoinPoint joinpoint , Exception ex){
        System.out.println("【AfterThrowing 通知】" + joinpoint.toString());
        System.out.println("ex = " + ex);
    }


    @Around(value="saveMethod()")
    public Object afterReturingMethod(ProceedingJoinPoint joinpoint ){
        Object obj = null;
        try{
            System.out.println("开启事务");
            Object args[] = joinpoint.getArgs();  // 10,20   0 ,0
            obj = joinpoint.proceed(args);


            System.out.println("提交事务");
        }catch (Throwable e) {
            System.out.println("回滚");
            throw new RuntimeException(e);
        } finally {

        }

        return obj;
    }
}